#!/usr/bin/perl
#pvrescan
require './lvm-lib.pl';
&ReadParse();
my $err_msg = 'abc';

sub get_md_info
{
    my ($pvinfo, @pv_info);
    $pvinfo = \@pv_info;
    $i=0;
    open(PV, "/sbin/fdisk -l /dev/md? 2>/dev/null |");
    while($line = <PV>) {
      $line =~ s/\r|\n//g;
      $line =~ s/#.*$//g;
      if ($line =~ /^Disk\s+(\/dev\/md\S):\s+\S+\s+GB/) {
        $name = $1;
        $pvinfo->[$i]->{'name'} = $name;
        $i++;
      }
      else {
         next;
      }
    }
    close(PV);
    return @pv_info;
}
sub get_pv_info
{
        my @pvinfo=();
        my @pvinfob;
        my $pv;
        open(PV, "/sbin/lvm pvs --units g --noheadings 2>/dev/null |");
        my $i = 0;
        while($line = <PV>) {
                $line =~ s/\r|\n//g;
                $line =~ s/#.*$//g;
                if ($line =~ /\s+(\S+)\s+(\S+)\s+\S+\s\S+\s+(\S+)G\s+(\S+)G/) {
                        $pv = $1;
                        $i++;
                        $pvinfo[$i]->{'pv'} = $pv;
                }
                elsif($line =~ /\s+(\S+)\s+(\S+)\s+\S+\s\S+\s+(\S+)G\s+0/){
                        $pv = $1;
                        $i++;
                        $pvinfo[$i]->{'pv'} = $pv;
                }
                elsif ($line =~ /\s+(\S+)\s+\S+\s+(\S+)\s+(\S+)G\s+(\S+)G/) {
                        $pv = $1;
                        $i++;
                        $pvinfo[$i]->{'pv'} = $pv;
                }
                else{
                        next;
                }
        }
        close(PV);
        foreach $pvi (@pvinfo) {
                if($pvi->{'pv'}){
                        push(@pvinfob, $pvi);
                }
        }
        return @pvinfob;
}
#main procedure
my @mdinfo;
my $md;
my @pvinfo;
my $p;
@pvinfo = get_pv_info();
@mdinfo = get_md_info();
my $found;
foreach $md (@mdinfo) {
        $found = 0;
        foreach $p (@pvinfo) {
                if ($p->{'pv'} eq $md->{'name'}){
                        $found = 1;
                        last;
                }
        }
        if(!$found){
                `/sbin/lvm pvcreate $md->{'name'}`;
        }
}
foreach $p (@pvinfo){
        $found = 0;
        foreach $md (@mdinfo) {
                if($md->{'name'} eq $p->{'pv'}) {
                        $found = 1;
                        last;
                }
        }
        if(!$found){
                `/sbin/lvm pvremove $p->{'pv'} -ff -y`;
        }
}

#goto ERROR_OUT;

&redirect("index.cgi");

ERROR_OUT:
&error_setup($text{'crt_err_title'});
&error($err_msg);
